/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mrroman.linksender.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.ResourceBundle;
import java.util.logging.Logger;

import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

import com.mrroman.linksender.Configuration;
import com.mrroman.linksender.gui.actions.SendMessageDialogAction;
import com.mrroman.linksender.ioc.In;
import com.mrroman.linksender.ioc.Init;
import com.mrroman.linksender.ioc.Locales;
import com.mrroman.linksender.ioc.Log;
import com.mrroman.linksender.ioc.Name;
import com.mrroman.linksender.ioc.ObjectStore;
import com.mrroman.linksender.sender.Message;
import com.mrroman.linksender.sender.MessageEvent;
import com.mrroman.linksender.sender.MessageListener;
import com.mrroman.linksender.sender.MessagePoint;
import javax.swing.SwingWorker;

/**
 *
 * @author gorladam
 */
@Name("gui.PopupPanel")
public class PopupPanel extends JPanel implements MessageListener {

    @Locales
    private ResourceBundle messages;
    @Log
    private Logger logger;
    @In
    private Configuration configuration;
    @In
    private ClipboardUtils clipboardUtils;
    @In
    private SendMessageDialogAction sendMessageDialogAction;
    private LinkedList<PopupLabel> labels;
    private JWindow frame;
    private JScrollPane scrollPane;
    private int addedLabels;

    @Init
    public void init() {

        labels = new LinkedList<PopupLabel>();
        frame = new JWindow();
        frame.setLayout(new BorderLayout());

        scrollPane = new JScrollPane(this);
        scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0));
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);
        //frame.setContentPane(scrollPane);
        JPanel blackPanel = new JPanel(new BorderLayout());
        //blackPanel.setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(8, 8, 8, 8)));
        blackPanel.setBorder(new LineBorder(Color.BLACK));
        blackPanel.add(scrollPane);
        frame.add(blackPanel);

        this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
        this.setBackground(configuration.getPopupPanelColor());
        //frame.setUndecorated(true);
        frame.setAlwaysOnTop(true);
        this.setOpaque(true);

        addedLabels = 0;

//        for (int i = 0; i < 10; i++) {
//            MessageEvent me = new MessageEvent(new Message("A"+i, "a  bb cccccccccc aaaa " + i));
//            PopupLabel pl = ObjectStore.getInstance().getObject(PopupLabel.class);
//            pl.setMessage(me.getMessage());
//            pl.addActionListener(new LabelActionListener(this));
//            labels.add(pl);
//        }
//
//        (new SwingWorker() {
//            @Override
//            protected Object doInBackground() throws Exception {
//                Thread.sleep(2000);
//                PopupPanel.this.showPopupLabels();
//                return null;
//            }
//        }).execute();

//        (new SwingWorker() {
//
//            @Override
//            protected Object doInBackground() throws Exception {
//                Thread.sleep(4000);
//                PrivateMessagePoint priv = ObjectStore.getInstance().getObject(PrivateMessagePoint.class);
//                byte[] me = new byte[]{127, 0, 0, 1};
//                InetAddress ip = InetAddress.getByAddress(me);
//                for (int i = 0; i < 8; i++) {
//                    //Thread.sleep(100);
//                    priv.sendMessage(new Message("A" + i, "a  bb cccccccccc aaaa " + i), ip);
//                }
//                return null;
//            }
//        }).execute();

//        (new SwingWorker() {
//
//            @Override
//            protected Object doInBackground() throws Exception {
//                Thread.sleep(4000);
//                MessagePoint mp = ObjectStore.getObject(MessagePoint.class);
//                mp.sendMessage(new Message("dmn", "wybaczcie spam - przetestujemy twittera ;)"));
//                Thread.sleep(2000);
//                for (int i = 0; i < 20; i++) {
//                    mp.sendMessage(new Message("nie ja", "http://onet.pl " + i));
//                }
//                return null;
//            }
//        }).execute();

    }

    @Override
    public void messageSend(MessageEvent event) {
        if ((event.getMessage().getFlags() & Message.MESSAGE_FLAG_HIDDEN) > 0) {
        } else {
            //System.out.println("***** " + event.getMessage().getFlags());
            if (configuration.isHideGroupMessages()
                    && (event.getMessage().getFlags() & Message.MESSAGE_FLAG_PRIVATE) == 0) {
                return;
            }

            if (ChatDialog.getActiveChatDialog() != null) {
                return;
            }

            if ((event.getMessage().getFlags() & Message.MESSAGE_FLAG_SELF) > 0) {
                return;
            }

            PopupLabel pl = ObjectStore.getObject(PopupLabel.class);
            if ((event.getMessage().getFlags() & Message.MESSAGE_FLAG_PRIVATE) > 0) {
                pl.setBackground(configuration.getPrivateMessageColor());
            } else if (event.getEvent() == MessageEvent.EventType.ERROR) {
                pl.setBackground(configuration.getErrorMessageColor());
            } else if (event.getEvent() == MessageEvent.EventType.INFO) {
                pl.setBackground(configuration.getInfoMessageColor());
            }
            pl.setMessage(event.getMessage());
            pl.addActionListener(new LabelActionListener(this));
            labels.add(pl);
            showPopupLabels();
        }
    }

    public void serverInfo(MessageEvent event) {
    }

    private class LabelActionListener implements ActionListener {

        private PopupPanel pp;

        public LabelActionListener(PopupPanel pp) {
            this.pp = pp;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            final PopupLabel popupLabel = (PopupLabel) e.getSource();


            if (e.getActionCommand().equals("REMOVE")) {
                synchronized (pp) {
                    pp.labels.remove(popupLabel);
                    pp.addedLabels--;
                    pp.remove((Component) e.getSource());
                    pp.showPopupLabels();
                }
            }

            if (e.getActionCommand().equals("REPLY")) {
                sendMessageDialogAction.actionPerformed(e);
            }

            if (e.getActionCommand().equals("COPY")) {
                clipboardUtils.copyText(popupLabel.getMessage().getMessage());
            }

            if (e.getActionCommand().equals("OPEN")) {
                MessageWindow window = ObjectStore.getObject(MessageWindow.class);
                window.setMessage(popupLabel.getMessage());
                window.setVisible(true);
            }
        }
    }

    public void showPopupLabels() {
        if (labels.size() == 0) {
            frame.setVisible(false);
            return;
        }
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                int heightCounter = 2;
                for (int i = addedLabels; i < labels.size(); i++) {
                    PopupLabel pl = labels.get(i);
                    PopupPanel.this.add(pl, 0);
                    heightCounter += pl.getPreferredSize().getHeight();
                }
                PopupPanel.this.validate();
                for (int i = 0; i < addedLabels; i++) {
                    PopupLabel pl = labels.get(i);
                    heightCounter += pl.getPreferredSize().getHeight();
                }

                addedLabels = labels.size();
                Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                Dimension dmin = new Dimension(screenSize.width / 4, 20);
                Dimension dmax = new Dimension(screenSize.width / 4, Math.min(heightCounter, screenSize.height / 2));
                frame.pack();
                frame.setMinimumSize(dmin);
                frame.setMaximumSize(dmax);
                frame.setPreferredSize(dmax);
                frame.pack();
                Point point = null;
                if (point == null) {
                    point = new Point(screenSize.width - frame.getWidth() - 50, screenSize.height - frame.getHeight() - 50);
                } else {
                    point.x = Math.min(screenSize.width - frame.getWidth() - 30, point.x);
                    point.y = Math.min(screenSize.height - frame.getHeight() - 30, point.y);
                }
                frame.setLocation(point.x, point.y);
                frame.setVisible(true);
            }
        });
    }

    public void hidePopupLabels() {
        frame.setVisible(false);
        labels.clear();
        this.removeAll();
        addedLabels = 0;
    }
}
